package cn.ycl.system.biz.order.controller;

import cn.ycl.auth.api.user.domain.User;
import cn.ycl.auth.api.user.feign.RemoteUserService;
import cn.ycl.constans.Constants;
import cn.ycl.constans.Result;
import cn.ycl.entity.UserInfoVO;
import cn.ycl.syslog.OperationEnum;
import cn.ycl.syslog.SystemLog;
import cn.ycl.system.api.order.domain.KillOrder;
import cn.ycl.system.biz.order.entity.CheckUserAndOrderParam;
import cn.ycl.system.biz.order.entity.KillOrderPageParam;
import cn.ycl.system.biz.order.entity.bo.KillOrderBO;
import cn.ycl.system.biz.order.entity.vo.KillOrderAndInfoVO;
import cn.ycl.system.biz.order.entity.vo.KillOrderVO;
import cn.ycl.system.biz.order.service.KillOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * (KillOrder)表控制层
 *
 * @author makejava
 * @since 2020-10-12 14:25:22
 */
@RestController
@RequestMapping("/killOrder")
public class KillOrderController {
    /**
     * 服务对象
     */
    @Resource
    private KillOrderService killOrderService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RemoteUserService remoteUserService;

    ConcurrentHashMap<String, Boolean> productSoldOutMap = new ConcurrentHashMap<>();

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/selectOne/{id}")
    public KillOrder selectOne(@PathVariable("id") Long id) {
        return this.killOrderService.queryById(id);
    }


    /**
     * 修改数据
     *
     * @param killOrder 前端需要传的数据
     * @return 请求结果
     */
    @PostMapping("/updateOrder")
    public Result updateOrder(@RequestBody KillOrder killOrder) {
        Integer update = killOrderService.update(killOrder);
        if (update > 0) {
            return Result.ok("修改成功");
        }
        return Result.fail("修改失败");
    }

    /**
     * 删除数据
     *
     * @param id 前端需要传的数据
     * @return 请求结果
     */
    @PostMapping("/deleteOrder/{id}")
    public Result deleteProduct(@PathVariable("id") Long id) {
        boolean result = killOrderService.deleteById(id);
        if (result) {
            return Result.ok("删除成功");
        }
        return Result.fail("删除失败");
    }

    /**
     * 新增数据
     *
     * @param killOrder 前端需要传的数据
     * @return 请求结果
     */
    @PostMapping("/insertOrder")
    public Result insertProduct(@RequestBody KillOrder killOrder) {
        Integer insert = killOrderService.insert(killOrder);
        if (insert > 0) {
            return Result.ok("新增成功");
        }
        return Result.fail("新增失败");
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param killOrder 实例对象
     * @return 对象列表
     */

    @GetMapping("/queryByOrder")
    public PageInfo<KillOrder> queryAll(@RequestBody KillOrder killOrder) {
        PageHelper.startPage(killOrder.getPageNum(), killOrder.getPageSize());
        List<KillOrder> killOrders = killOrderService.queryByOrder(killOrder);
        return new PageInfo<>(killOrders);
    }


    /**
     * 优化的秒杀产品订单
     *
     * @param killOrderVO 订单信息
     * @return 对象列表
     */
    @SystemLog(value = "秒杀操作", type = OperationEnum.KILL)
    @PostMapping("/secKillRedis")
    public Result secKillRedis(@RequestBody KillOrderVO killOrderVO) {
        UserInfoVO user = remoteUserService.getUserInfo();
        if (Objects.isNull(user)) {
            return Result.fail("未登录");
        }
        KillOrderBO killOrderBO = new KillOrderBO();
        BeanUtils.copyProperties(killOrderVO, killOrderBO);
        killOrderBO.setUserId(user.getUserId());
        User user1 = new User();
        BeanUtils.copyProperties(user, user1);
        killOrderBO.setUser(user1);
        if (productSoldOutMap.containsKey(String.valueOf(killOrderBO.getProductId()))) {
            return Result.fail("商品已售卖完毕，很遗憾您未能秒杀成功");
        }
        Long orderId;
        try {
            Long stock = stringRedisTemplate.opsForValue().decrement(Constants.REDIS_PRODUCT_STOCK_PREFIX + killOrderBO.getProductId());
            if (stock != null && stock < 0) {
                //设置售完标记
                productSoldOutMap.put(String.valueOf(killOrderBO.getProductId()), true);
                //使得redis中的库存最少都为0，而不是负数
                stringRedisTemplate.opsForValue().increment(Constants.REDIS_PRODUCT_STOCK_PREFIX + killOrderBO.getProductId());
                return Result.fail("商品已售卖完毕，很遗憾您未能秒杀成功");
            }
            orderId = killOrderService.secKillRedis(killOrderBO);
        } catch (Exception e) {
            //如果抛异常，未成功保存订单，需要将redis的库存+1，与数据库保持一致
            stringRedisTemplate.opsForValue().increment(Constants.REDIS_PRODUCT_STOCK_PREFIX + killOrderBO.getProductId());
            return Result.fail("创建订单失败");
        }
        return Result.ok(orderId);
    }

    /**
     * 通过订单编号获取秒杀订单
     *
     * @param orderId 订单编号
     * @return 秒杀订单
     */
    @GetMapping("/getKillOrder")
    public KillOrderAndInfoVO getKillOrder(Long orderId) {
        return killOrderService.getKillOrder(orderId);
    }

    /**
     * 直接改变订单状态为已支付，少用
     *
     * @param killOrder 订单
     * @return 结果
     */
    @PostMapping("/changeKillOrder")
    public Result<Object> changeKillOrder(@RequestBody KillOrder killOrder) {
        killOrderService.changeKillOrder(killOrder);
        return Result.ok();
    }

    /**
     * 获取订单列表
     *
     * @param killOrderPageParam 请求参数
     * @return 结果
     */
    @GetMapping("/getKillOrderList")
    public PageInfo<KillOrderBO> getKillOrderList(KillOrderPageParam killOrderPageParam) {
        PageHelper.startPage(killOrderPageParam.getPageNum(), killOrderPageParam.getPageSize());
        List<KillOrderBO> killOrders = killOrderService.getKillOrderPage(killOrderPageParam);
        return new PageInfo<KillOrderBO>(killOrders);
    }

    /**
     * 检查订单是否为当前用户所拥有
     * @param checkUserAndOrderParam 请求参数
     * @return 结果
     */
    @PostMapping("/checkUserAndOrder")
    public Result checkUserAndOrder(@RequestBody CheckUserAndOrderParam checkUserAndOrderParam) {
        Boolean result = killOrderService.checkUserAndOrder(checkUserAndOrderParam.getOrderId());
        return Result.ok(result);
    }

    /**
     * 订单支付
     * @param killOrder 请求参数
     * @return 结果
     */
    @PostMapping("/orderToPay")
    public Result orderToPay(@RequestBody KillOrder killOrder) {
        Long orderId = killOrder.getId();
        KillOrder killOrder2 = killOrderService.queryById(orderId);
        killOrder2.setAddress(killOrder.getAddress());
        killOrder2.setStatus(3);
        UserInfoVO userInfo = remoteUserService.getUserInfo();
        if(!userInfo.getUserId().equals(killOrder.getUserId())){
            return Result.fail("非订单持有人，不可支付");
        }
        Integer result = killOrderService.update(killOrder2);
        return Result.ok(result);
    }

    /**
     * 订单接单
     * @param checkUserAndOrderParam 请求参数
     * @return 结果
     */
    @PostMapping("/orderReceiving")
    public Result orderReceiving(@RequestBody CheckUserAndOrderParam checkUserAndOrderParam) {
        Long orderId = checkUserAndOrderParam.getOrderId();
        KillOrder killOrder = killOrderService.queryById(orderId);
        killOrder.setStatus(4);
        Integer result = killOrderService.update(killOrder);
        return Result.ok(result);
    }

    /**
     * 订单发货
     * @param checkUserAndOrderParam 请求参数
     * @return 结果
     */
    @PostMapping("/orderShipping")
    public Result orderShipping(@RequestBody CheckUserAndOrderParam checkUserAndOrderParam) {
        Long orderId = checkUserAndOrderParam.getOrderId();
        KillOrder killOrder = killOrderService.queryById(orderId);
        killOrder.setStatus(5);
        Integer result = killOrderService.update(killOrder);
        return Result.ok(result);
    }

    /**
     * 拒绝接单（拒绝订单）
     * @param checkUserAndOrderParam 请求参数
     * @return 结果
     */
    @PostMapping("/orderReject")
    public Result orderReject(@RequestBody CheckUserAndOrderParam checkUserAndOrderParam) {
        Long orderId = checkUserAndOrderParam.getOrderId();
        KillOrder killOrder = killOrderService.queryById(orderId);
        killOrder.setStatus(10);
        Integer result = killOrderService.update(killOrder);
        return Result.ok(result);
    }

    /**
     * 完成订单
     * @param checkUserAndOrderParam 请求参数
     * @return 结果
     */
    @PostMapping("/orderComplete")
    public Result orderComplete(@RequestBody CheckUserAndOrderParam checkUserAndOrderParam) {
        Long orderId = checkUserAndOrderParam.getOrderId();
        KillOrder killOrder = killOrderService.queryById(orderId);
        killOrder.setStatus(7);
        Integer result = killOrderService.update(killOrder);
        return Result.ok(result);
    }


    /**
     * 退款
     * @param checkUserAndOrderParam 请求参数
     * @return 结果
     */
    @PostMapping("/orderRefund")
    public Result orderRefund(@RequestBody CheckUserAndOrderParam checkUserAndOrderParam) {
        Long orderId = checkUserAndOrderParam.getOrderId();
        KillOrder killOrder = killOrderService.queryById(orderId);
        killOrder.setStatus(8);
        Integer result = killOrderService.update(killOrder);
        return Result.ok(result);
    }




}